package llTest;
//v_2.0.0_build_20161024
import java.io.File;
import java.io.IOException;
import de.bwaldvogel.liblinear.Feature;
import de.bwaldvogel.liblinear.Linear;
import de.bwaldvogel.liblinear.Model;
import de.bwaldvogel.liblinear.Parameter;
import de.bwaldvogel.liblinear.Problem;
import de.bwaldvogel.liblinear.SolverType;

public class FloorIdentifier{
    public String generateModel(String filePath) throws IOException{
    	
    	long a1=System.currentTimeMillis();
    	Data data=new Data();
    	data.loadData(filePath);
        Feature[][] featureMatrix = data.getFeatureMatrix();
        //loading target value
        double[] targetValue=data.getTargetValue();
        
        Problem problem = new Problem();
        problem.l = targetValue.length; // number of training examples：训练样本数
        problem.n = data.getFeatureDimension(); // number of features：特征维数
        System.out.println("特征个数为："+data.getFeatureDimension()+"。");
        problem.x = featureMatrix; // feature nodes：特征数据
        problem.y = targetValue; // target values：类别

        SolverType solver = SolverType.L2R_LR; // -s 0
        double C = 1.0;    // cost of constraints violation
        double eps = 0.01; // stopping criteria
        
        Parameter parameter = new Parameter(solver, C, eps);
        Model model = Linear.train(problem, parameter);
        String seperater=File.separator;
        String modelPath = filePath.substring(0,filePath.lastIndexOf("floor.data")-1)+seperater+"model";
        File modelFile = new File(modelPath);
        model.save(modelFile);        
        // load model or use it directly
        model = Model.load(modelFile);
        
        long b1=System.currentTimeMillis();
        System.out.println("训练时间为："+(b1-a1)+"毫秒。");

        long a=System.currentTimeMillis();
        int m=0;
        int all=data.getPointNumber();
        for(int n=0;n<all;n++){
        Feature[] testNode = data.getSample(n);
        double prediction = Linear.predict(model, testNode);
        if(Math.abs(targetValue[n]-prediction)>0.01){
        		m=m+1;
        		System.out.println((n+1)+" 预测为："+prediction+"，实际为："+targetValue[n]);
        	}
        }
        
        System.out.println("出错的个数为："+m+"； 总个数为："+all+"。");
        long b=System.currentTimeMillis();
        System.out.println("测试时间为："+(b-a)+"毫秒。");
        return modelPath;
    }
}